package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.MissionCenterAddDTO;
import org.jsola.hr.dto.MissionCenterExportWrongDTO;
import org.jsola.hr.dto.MissionCenterExtraAddDTO;
import org.jsola.hr.dto.MissionCenterUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.MissionCenterQuery;
import org.jsola.hr.service.IMissionCenterService;
import org.jsola.hr.vo.MissionCenterImportVO;
import org.jsola.hr.vo.MissionCenterListVO;
import org.jsola.hr.vo.MissionCenterStatisticsVO;
import org.jsola.hr.vo.MissionCenterVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.validation.Valid;


/**
 * 任务调度中心任务表
 *
 * @author zhr
 */
@RestController("hrMissionCenterController")
@RequestMapping(HrConstants.API_PATH + "/v1/missionCenters")
public class MissionCenterController implements IMissionCenterControllerAPI {

    @Autowired
    private IMissionCenterService missionCenterService;

    @Override
    @PostMapping
    public Result<MissionCenterVO> save(@Valid @RequestBody MissionCenterAddDTO missionCenterAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增任务调度中心任务表权限校验

        return Result.success(
                missionCenterService.save(missionCenterAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody MissionCenterUpdateDTO missionCenterUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改任务调度中心任务表权限校验

        int count = missionCenterService.update(missionCenterUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{missionCenterId}")
    public Result<Integer> delete(@PathVariable String missionCenterId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除任务调度中心任务表权限校验

        int count = missionCenterService.deleteByIds(tokenUser, missionCenterId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] missionCenterIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除任务调度中心任务表权限校验

        int count = missionCenterService.deleteByIds(tokenUser, missionCenterIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{missionCenterId}")
    public Result<MissionCenterVO> findById(@PathVariable String missionCenterId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看任务调度中心任务表权限校验

        return Result.success(
                missionCenterService.selectById(missionCenterId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<MissionCenterListVO>> listAll(@Valid MissionCenterQuery missionCenterQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看任务调度中心任务表权限校验

        return Result.success(
                missionCenterService.select(missionCenterQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<MissionCenterListVO>> page(@Valid MissionCenterQuery missionCenterQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                missionCenterService.selectPage(missionCenterQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("/parseImport")
    public Result<MissionCenterImportVO> parseImport(@RequestParam("file") MultipartFile file) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验
        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                missionCenterService.parseExcel(excelFile, tokenUser)
        );
    }

    @Override
    @PostMapping("/saveExcel")
    public Result<Integer> saveExcel(@Valid @RequestBody MissionCenterExtraAddDTO missionCenterExtraAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                missionCenterService.saveExcel(missionCenterExtraAddDTO, tokenUser)
        );
    }

    @Override
    @GetMapping("/selectTopStatistics")
    public Result<MissionCenterStatisticsVO> selectTopStatistics(@Valid MissionCenterQuery missionCenterQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                missionCenterService.selectTopStatistics(missionCenterQuery, tokenUser)
        );
    }

    @Override
    @GetMapping("/selectReceiveTopStatistics/{missionCenterId}")
    public Result<MissionCenterStatisticsVO> selectReceiveTopStatistics(@PathVariable String missionCenterId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                missionCenterService.selectReceiveTopStatistics(missionCenterId, tokenUser)
        );
    }

    @Override
    @GetMapping("/selectAllReceiveTopStatistics")
    public Result<MissionCenterStatisticsVO> selectAllReceiveTopStatistics(@Valid MissionCenterQuery missionCenterQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                missionCenterService.selectAllReceiveTopStatistics(missionCenterQuery, tokenUser)
        );
    }

    @Override
    @GetMapping("/viewMission")
    public Result<Page<MissionCenterListVO>> viewMission(@Valid MissionCenterQuery missionCenterQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                missionCenterService.viewMission(missionCenterQuery, tokenUser)
        );
    }

    @Override
    @PutMapping("/confirmReceive/{missionCenterId}")
    public Result<Boolean> confirmReceive(@PathVariable String missionCenterId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                missionCenterService.confirmReceive(missionCenterId, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportWrongsData")
    public ResponseEntity<Resource> exportWrongsData(@Valid @RequestBody MissionCenterExportWrongDTO exportWrongDTO) {
        TokenUser tokenUser = UserContext.getUser();
        String excelFilePath = missionCenterService.exportWrongsDataPath(exportWrongDTO, tokenUser);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath)
                .getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @GetMapping("/createUserList")
    public Result<List<UserDO>> selectAllCreateUserBySite() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                missionCenterService.selectAllCreateUserBySite(tokenUser)
        );
    }

}

